<script setup name="inform_publish">
import OAMain from "@/components/OAMain.vue";
import {reactive, ref, onBeforeUnmount, shallowRef, onMounted} from "vue";
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import staffhttp from "@/api/staffhttp.js";
import {ElMessage} from "element-plus";
import {useAuthStore} from "@/stores/auth.js";
import informhttp from "@/api/informhttp.js";
let informForm = reactive({
  title: "",
  content: "",
  department_ids: []
})
const rules = reactive({
  title: [{
    required: true,
    message: "请输入标题",
    trigger: "blur",
  }],
  content: [{
    required: true,
    message: "请输入内容",
    trigger: "blur",
  }],
  department_ids: [{
    required: true,
    message: "请选择部门！",
    trigger: "change",
  }]
})
let formRef = ref()
let formLabelWidth = "100px"
let departments = ref([])
const authStore = useAuthStore()
onMounted(async () => {
  try {
    let data = await staffhttp.getAllDepartments()
    departments.value = data.data.results
  } catch (err) {
    ElMessage.error(err)
  }
})
// wangEdit富文本编辑器配置
const editorRef = shallowRef()
const valueHtml = ref('<p>hello</p>')
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: import.meta.env.VITE_API_URL + '/image/upload',
      fieldName: 'image',
      maxFileSize: 0.5 * 1024 * 1024,
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      headers: {
        Authorization: "JWT " + authStore.token
      },
      timeout: 6 * 1000,
      customInsert(res, insertFn) {
        if (res.errno == 0) {
          let data = res.data;
          let url = import.meta.env.VITE_API_URL + data.url
          let href = import.meta.env.VITE_API_URL + data.href
          let alt = data.alt;
          insertFn(url, alt, href)

        } else {
          ElMessage.error(res.message)
        }
      },
      onFailed(file, res) {
        ElMessage.error(`${file.name} 上传失败`, res)
      },

      // 上传错误，或者触发 timeout 超时
      onError(file, err, res) {
        if(file.size > 0.5 * 1024 * 1024) {
          ElMessage.error("图片文件最大不能超过0.5MB")
        }else{
          ElMessage.error(`${file.name} 上传出错`, err.message)
        }
      },
    }

  }
}
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
let mode = "default"
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

// 富文本编辑器结束//////////////////////////////////////
const onSubmitPublish = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let data = await informhttp.publishInform(informForm)
        ElMessage.success("添加" + data.title + "成功")
      }catch(err) {
        ElMessage.error(err.message)
      }
    }
  })
}

</script>

<template>
  <OAMain title="发布通知">
    <el-card>
      <el-form :model="informForm" :rules="rules" ref="formRef">
        <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model="informForm.title" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="部门可见" :label-width="formLabelWidth" prop="department_ids">
          <el-select v-model="informForm.department_ids" multiple>
            <el-option :value="0" label="所有部门"></el-option>
            <el-option v-for="item in departments" :label="item.name" :value="item.id" :key="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth" prop="content">
          <div style="border: 1px solid #ccc; width: 100%; ">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
                v-model='informForm.content'
            />
          </div>
        </el-form-item>
        <el-form-item>
          <div style="text-align: right; width: 100%">
            <el-button @click="onSubmitPublish">发布通知</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </OAMain>
</template>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped>

</style>